home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / CPTUTT22.ZIP / CHAP03.TXT < prev    next >
Text File  |  1992-01-20  |  14KB  |  295 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.                                                        Chapter 3
  7.                                                         POINTERS
  8.  
  9. Because pointers are so important in C and C++, this chapter will
  10. review some of the more important topics concerning pointers.  Even
  11. if you are extremely conversant in the use of pointers, you should
  12. not completely ignore this chapter because some new material unique
  13. to C++ is presented here.
  14.  
  15.  
  16. POINTER REVIEW
  17. _________________________________________________________________
  18.  
  19. Examine the program named POINTERS.CPP for a     ================
  20. simple example of the use of pointers.  This is    POINTERS.CPP
  21. a pointer review and if you are comfortable with ================
  22. the use of pointers, you can skip this example
  23. program completely.
  24. A pointer in either ANSI-C or C++ is declared with an asterisk
  25. preceding the variable name.  The pointer is then a pointer to a
  26. variable of that one specific type and should not be used with
  27. variables of other types.  Thus pt_int is a pointer to an integer
  28. type variable and should not be used with any other type.  Of
  29. course, an experienced C programmer knows that it is simple to
  30. coerce the pointer to be used with some other type by using a cast,
  31. but he must assume the responsibility for its correct usage.
  32.  
  33. In line 12 the pointer named pt_int is assigned the address of the
  34. variable named pig and line 13 uses the pointer named pt_int to add
  35. the value of dog to the value of pig because the asterisk
  36. dereferences the pointer in exactly the same manner as standard C.
  37. The address is used to print out the value of the variable pig in
  38. line 14 illustrating the use of a pointer with the stream output
  39. operator cout.  Likewise, the pointer to float named pt_float is
  40. assigned the address of x, then used in a trivial calculation in
  41. line 18.
  42.  
  43. If you are not completely comfortable with this trivial program
  44. using pointers, you should review the use of pointers in any good
  45. C programming book or Coronado Enterprises C tutorial before
  46. proceeding on because we will assume that you have a thorough
  47. knowledge of pointers throughout the remainder of this tutorial.
  48. It is not possible to write a C program of any significant size or
  49. complexity without the use of pointers.
  50.  
  51.  
  52. CONSTANT POINTERS AND POINTERS TO CONSTANTS
  53. _________________________________________________________________
  54.  
  55. The definition of C++ allows a pointer to a constant to be defined
  56. such that the value to which the pointer points cannot be changed
  57.  
  58.                                                          Page 3-1
  59.  
  60.                                              Chapter 3 - Pointers
  61.  
  62. but the pointer itself can be moved to another variable or
  63. constant.  The method of defining a pointer to a constant is
  64. illustrated in line 22.  In addition to a pointer to a constant,
  65. you can also declare a constant pointer, one that cannot be
  66. changed.  Line 23 illustrates this.  Note that neither of these
  67. pointers are used in illustrative code.
  68.  
  69. Either of these constructs can be used to provide additional
  70. compile time checking and improve the quality of your code.  If you
  71. know a pointer will never be moved due to its nature, you should
  72. define it as a constant pointer.  If you know that a value will not
  73. be changed, it can be defined as a constant and the compiler will
  74. tell you if you ever inadvertently attempt to change it.
  75.  
  76.  
  77. A POINTER TO VOID
  78. _________________________________________________________________
  79.  
  80. The pointer to void is actually a part of the ANSI-C standard but
  81. is relatively new so it is commented upon here.  A pointer to void
  82. can be assigned the value of any other pointer type.  You will
  83. notice that the pointer to void named general is assigned an
  84. address of an int type in line 15 and the address of a float type
  85. in line 20 with no cast and no complaints from the compiler.  This
  86. is a relatively new concept in C and C++.  It allows a programmer
  87. to define a pointer that can be used to point to many different
  88. kinds of things to transfer information around within a program.
  89. A good example is the malloc() function which returns a pointer to
  90. void.  This pointer can be assigned to point to any entity, thus
  91. transferring the returned pointer to the correct type.
  92.  
  93. A pointer to void is aligned in memory in such a way that it can
  94. be used with any of the simple predefined types available in C++,
  95. or in ANSI-C for that matter.  They will also align with any
  96. compound types the user can define since compound types are
  97. composed of the simpler types.
  98.  
  99. Be sure to compile and execute this program.
  100.  
  101.  
  102. DYNAMIC ALLOCATION AND DEALLOCATION
  103. _________________________________________________________________
  104.  
  105. Examine the program named NEWDEL.CPP for our     ================
  106. first example of the new and delete operators.      NEWDEL.CPP
  107. The new and delete operators do dynamic          ================
  108. allocation and deallocation in much the same
  109. manner that malloc() and free() do in your old
  110. favorite C implementation.
  111.  
  112. During the design of C++, it was felt that since dynamic allocation
  113. and deallocation are such a heavily used part of the C programming
  114. language and would also be heavily used in C++, it should be a part
  115. of the language, rather than a library add-on.  The new and delete
  116.  
  117.                                                          Page 3-2
  118.  
  119.                                              Chapter 3 - Pointers
  120.  
  121. operators are actually a part of the C++ language and are
  122. operators, much like the addition operator or the assignment
  123. operator.  They are therefore very efficient, and are very easy to
  124. use as we will see in this example program.
  125.  
  126. Lines 14 and 15 illustrate the use of pointers in the tradition of
  127. C and line 16 illustrates the use of the new operator.  This
  128. operator requires one modifier which must be a type as illustrated
  129. here.  The pointer named point2 is now pointing at the dynamically
  130. allocated integer variable which exists on the heap, and can be
  131. used in the same way that any dynamically allocated variable is
  132. used in ANSI-C.  Line 18 illustrates displaying the value on the
  133. monitor which was assigned in line 17.
  134.  
  135. Line 20 allocates another new variable and line 21 causes point2
  136. to refer to the same dynamically allocated variable as point1 is
  137. pointing to.  In this case, the reference to the variable that
  138. point2 was previously pointing to has been lost and it can never
  139. be used or deallocated.  It is lost on the heap until we return to
  140. the operating system when it will be reclaimed for further use, so
  141. this is obviously not good practice.  Note that point1 is
  142. deallocated with the delete operator in line 25, and point2 can not
  143. actually be deleted.  Since the pointer point1 itself is not
  144. changed, it is actually still pointing to the original data on the
  145. heap.  This data could probably be referred to again using point1,
  146. but it would be terrible programming practice since you have no
  147. guarantee what the system will do with the pointer or the data.
  148. The data storage is returned to the free list to be allocated in
  149. a subsequent call, and will soon be reused in any practical
  150. program.
  151.  
  152. Since the delete operator is defined to do nothing if it is passed
  153. a NULL value, it is legal to ask the system to delete the data
  154. pointed to by a pointer with the value of NULL, but nothing will
  155. actually happen.  It is actually wasted code.  The delete operator
  156. can only be used to delete data allocated by a new operator.  If
  157. the delete is used with any other kind of data, the operation is
  158. undefined and anything can happen.  According to the ANSI standard,
  159. even a system crash is a legal result of this illegal operation,
  160. and can be defined as such by the compiler writer.
  161.  
  162. In line 27, we declare some floating point variables.  You will
  163. remember that in C++ the variables do not have to be declared at
  164. the beginning of a block.  A declaration is an executable statement
  165. and can therefore appear anywhere in a list of executable
  166. statements.  One of the float variables is allocated within the
  167. declaration to illustrate that this can be done.  Some of the same
  168. operations are performed on these float type variables as were done
  169. on the int types earlier.
  170.  
  171. Some examples of the use of a structure are given in lines 35
  172. through 41 and should be self explanatory.
  173.  
  174.  
  175.  
  176.                                                          Page 3-3
  177.  
  178.                                              Chapter 3 - Pointers
  179.  
  180. Finally, since the new operator requires a type to determine the
  181. size of the dynamically allocated block, you may wonder how you can
  182. allocate a block of arbitrary size.  This is possible by using the
  183. construct illustrated in line 47 where a block of 37 char sized
  184. entities, which will be 37 bytes, is allocated.  A block of 133
  185. bytes greater than the size of the date structure is allocated in
  186. line 49.  It is therefore clear that the new operator can be used
  187. with all of the flexibility of the malloc() function which you are
  188. familiar with.
  189.  
  190. The standard functions which you have been using in C for dynamic
  191. memory management, malloc(), calloc(), and free(), are also
  192. available for use in C++ and can be used in the same manner they
  193. were used in C.  The new and delete operators should not be
  194. intermixed with the older function calls since the results may be
  195. unpredictable.  If you are updating code with the older function
  196. calls, continue to use them for any additions to the code.  If you
  197. are designing and coding a new program you should use the newer
  198. constructs because they are a built in part of the language rather
  199. than an add on and are therefore more efficient.
  200.  
  201. Be sure to compile and execute this program.
  202.  
  203.  
  204.  
  205. POINTERS TO FUNCTIONS
  206. _________________________________________________________________
  207.  
  208. Examine the program named FUNCPNT.CPP for an      ===============
  209. example of using a pointer to a function.  It       FUNCPNT.CPP
  210. must be pointed out that there is nothing new     ===============
  211. here, the pointer to a function is available in
  212. ANSI-C as well as in C++ and works in the manner
  213. described here for both languages.  It is not regularly used by
  214. most C programmers, so it is defined here as a refresher.  If you
  215. are comfortable with the use of pointers to functions, you can skip
  216. this discussion entirely.
  217.  
  218. There is nothing unusual about this program except for the pointer
  219. to a function declared in line 7.  This declares a pointer to a
  220. function which returns nothing (void) and requires a single formal
  221. parameter, a float type variable.  You will notice that all three
  222. of the functions declared in lines 4 through 6 fit this profile and
  223. are therefore candidates to be called with this pointer.  If you
  224. have not used prototyping in C, these lines will look strange to
  225. you.  Don't worry about them at this point since we will study
  226. prototyping in the next chapter of this tutorial.
  227.  
  228. Observe that in line 14 we call the function print_stuff() with the
  229. parameter pi and in line 15 we assign the function pointer named
  230. function_pointer the value of print_stuff() and use the function
  231. pointer to call the same function again in line 16.  Lines 14 and
  232. 16 are therefore identical in what is accomplished because of the
  233. pointer assignment in line 15.  In lines 17 through 22, a few more
  234.  
  235.                                                          Page 3-4
  236.  
  237.                                              Chapter 3 - Pointers
  238.  
  239. illustrations of the use of the function pointer are given.  You
  240. will be left to study these on your own.
  241.  
  242. Since we assigned the name of a function to a function pointer, and
  243. did not get an assignment error, the name of a function must be a
  244. pointer to that function.  This is exactly the case.  A function
  245. name is a pointer to that function, but it is a pointer constant
  246. and cannot be changed.  This is exactly the case we found when we
  247. studied arrays in ANSI-C at some point in our C programming
  248. background.  An array name is a pointer constant to the first
  249. element of the array.
  250.  
  251. Since the name of the function is a constant pointer to that
  252. function, we can assign the name of the function to a function
  253. pointer and use the function pointer to call the function.  The
  254. only caveat is that the return value and the number and types of
  255. parameters must be identical.  Most C and C++ compilers will not,
  256. and in fact, can not warn you of type mismatches between the
  257. parameter lists when the assignments are made.  This is because the
  258. assignments are done at runtime when no type information is
  259. available to the system, rather than at compile time when all type
  260. information is available.
  261.  
  262. The use and operation of pointers must be thoroughly understood
  263. when we get to the material on dynamic binding and polymorphism
  264. later in this tutorial.  It will be discussed in detail at that
  265. time.
  266.  
  267. Be sure to compile and execute this program.
  268.  
  269.  
  270. PROGRAMMING EXERCISES
  271. _________________________________________________________________
  272.  
  273.  
  274. 1.   When dynamically allocated data is deleted, it is still
  275.      actually in memory, stored on the heap.  Repeat the output
  276.      statement from line 23 of NEWDEL.CPP immediately following the
  277.      delete in line 25 to see if the values are really still there.
  278.      Repeat it once again just prior to the end of the program when
  279.      the data spaces should have been written over to see if you
  280.      get garbage out.  Even if your compiler reports the correct
  281.      data, it is terrible practice to count on this data still
  282.      being there because in a large dynamic program, the heap space
  283.      will be used repeatedly.
  284.  
  285. 2.   Add a function to FUNCPNT.CPP which uses a single integer for
  286.      a parameter and attempt to call it by using the function
  287.      pointer to see if you get the correct data into the function.
  288.  
  289.  
  290.  
  291.  
  292.  
  293.  
  294.                                                          Page 3-5
  295.